/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.EDemoSerial;
import com.sun.spot.sensorboard.peripheral.ILightSensor;
import com.sun.spot.util.Utils;
import com.sun.squawk.util.StringTokenizer;
import java.io.DataInputStream;
import java.io.IOException;

/**
 *
 * @author me
 */
public class GPSReading {
    private static DataInputStream dio;
    private double[] gpsReading = new double[3];
    private int lightReading;
    private long time;
    private static final float HDOP_CUTOFF = (float)7.0;
    private static ILightSensor lightSensor = EDemoBoard.getInstance().getLightSensor();
    public static final int SIZE = 8*4 + 4;

    public double[] getGpsReading() {
        return gpsReading;
    }

    public int getLightReading() {
        return lightReading;
    }

    public long getTime() {
        return time;
    }

    public static void init() {
        try {
            EDemoSerial serial = new EDemoSerial();
            serial.setUSARTParams(4800, 8, "none", 2);
            dio = serial.openDataInputStream();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public GPSReading() {
        clearUART();
        waitForMessage();
        while (!isGPGGA(readMessage())) {
            Utils.sleep(100);
        }
        try {
            lightReading = lightSensor.getAverageValue();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        time = System.currentTimeMillis();
    }

    private double convert(double value) {
        value /= 100;
        int degrees = (int)Math.floor(value);
        value -= degrees;
        return value * 100/60 + degrees;
    }

    private boolean isGPGGA(String gpsData) {
        StringTokenizer tokenizer = new StringTokenizer(gpsData, ",");
        String label = tokenizer.nextToken();
        System.out.println(label);
        if (label.equals("$GPGGA")) {
            try {
                tokenizer.nextToken();
                gpsReading[0]=convert (Double.parseDouble(tokenizer.nextToken()));
                System.out.println("WHEE, READING!");
                System.out.println(gpsReading[0]);
                if (tokenizer.nextToken().equals("S")) {
                    gpsReading[0] *=-1;
                }
                System.out.println(gpsReading[0]);
                gpsReading[1]=convert (Double.parseDouble(tokenizer.nextToken()));
                System.out.println(gpsReading[1]);
                if (tokenizer.nextToken().equals("W")) {
                    gpsReading[1] *=-1;
                }
                System.out.println(gpsReading[1]);
                if (Integer.parseInt(tokenizer.nextToken())>0) {
                    tokenizer.nextToken();
                    gpsReading[2] = Double.parseDouble(tokenizer.nextToken());
                    System.out.println(gpsReading[2]);
                    if (gpsReading[2] <= HDOP_CUTOFF) {
                        //make packet
                        return true;
                    }
                }
            } catch (Exception e) {
                System.out.println("GGA Exception: " + e);
            }
        }
        return false;
    }

    private void waitForMessage() {
        byte val = 0;
        char dollarSign = '$';
        System.out.println("waiting...");
        while (val != dollarSign) {
            try {
                val = dio.readByte();
                //pause(10);
            } catch (Exception e) {
                //pause(10);
                e.printStackTrace();
            }
        }
    }

    private String readMessage() {
        StringBuffer sBuff = new StringBuffer();
        sBuff.append('$');
        byte val = 0;
        System.out.println("receiving...");
        //System.out.println((char)val);
        while(true) {
            try {
                val = dio.readByte();
                switch (val) {
                    case 10:
                        return sBuff.toString();
                    case (byte)('$'):
                        return readMessage();
                    default:
                        sBuff.append((char)val);
                }
                //pause(100);
            } catch (Exception e) {
                System.out.println("receive error...pause(10)");
                // e.printStackTrace();
                Utils.sleep(10);
            }
        }
    }

    private void clearUART() {
        try {
            dio.skip(dio.available()-5);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
